<template>
  <div class="category">
    <div v-for="(level, index) in selectedCategories" :key="index" class="category-level">
      <div class="category-label"lass="category-label">{{ selectLevels[index]?.label }}</div>
      <div class="category-list">
        <div
          v-for="category in level"
          :key="category.id"
          :class="['category-item', { active: isSelected(category, index) }]"
          @click="selectCategory(category, index)"
        >
          {{ category.name }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, computed, onMounted } from 'vue'
  import sheep from '@/sheep'

  // 定义组件的props
  const props = defineProps({
    isTk: {
      type: Boolean,
      default: false
    },
    selectCategoryId:{
      type: Number,
      default: 170
    }
  });

  // 定义emit
  const emit = defineEmits(['update:selected'])

  const currentYear = new Date().getFullYear()
  const years = [{name: '全部'}, {id: currentYear, name: `${currentYear}`}, {id: currentYear - 1, name: `${currentYear - 1}`}]
  const categoryLabels = [{label: '项目', field: 'category1'}, {label: '科目', field: 'category2'}];
 // const categoryLabels = [{label: '项目', field: 'category1'}, {label: '科目', field: 'category2'}];
  const yearsLabel = {label: '年份', field: 'year'}
  const tikuTypeLabel = {label: '类型', field: 'tikutype'}

  function addAllChildrenItem(item, lastLevel) {
    return {
      id: item.id,
      name: item.name,
      children: item.children?.length ? [
        {name: '全部', children: [...lastLevel]},
        ...item.children.map(child => addAllChildrenItem(child, lastLevel))
      ] : [...lastLevel]
    }
  }

  // 存储每一层选中的分类
  const selection = ref([]);
  const categories = ref([]);
  onMounted(() => {

    if (props.isTk) {
      sheep.$api.course.getCourseCategoryWithTK().then((res) => {
        const cates = res.data.categories.children;
        let tikuTypes = res.data.tikutype.map(item => ({id: item, name: item}));
        tikuTypes = [{name: '全部'}, ...tikuTypes];
        categories.value = cates.map(item => addAllChildrenItem(item, tikuTypes));
        selectCategory(categories.value[0], 0);
      });
    } else {
      sheep.$api.course.getBanxingCategory().then((res) => {
        //categories.value = res.data.children.map(item => addAllChildrenItem(item, years));
        categories.value = res.data.childrenshow;
        const index = categories.value.findIndex(item => item.id === parseInt(props.selectCategoryId))
        selectCategory(categories.value[index], 1);
      });
    }
  });

  // 每次选中一个元素后，重新计算其所有子层级的元素
  const selectCategory = (category, level) => {
    // 清除当前层级后的所有选择
    selection.value = selection.value.slice(0, level)
    // 添加新的选择
    selection.value.push(category)

    // 自动选择子层级的第一个选项
    let current = category;
    while (current.children?.length) {
      current = current.children[0];
      selection.value.push(current);
    }

    const selected = selection.value.map((item, index) => ({id: item.id, field: selectLevels.value[index].field}));
    const result = selected.reduce((acc, item) => {
      if (item.id) {
        acc[item.field] = item.id;
      }
      return acc;
    }, {});
    emit('update:selected', result);
  }

  // 计算当前要显示的所有层级的分类
  const selectedCategories = computed(() => {
    const result = [categories.value]
    selection.value.forEach(item => {
      if (item.children?.length) {
        result.push(item.children)
      }
    });

    return result;
  });

  const selectLevels = computed(() => {
    if (props.isTk) {
      return [...categoryLabels.slice(0, selection.value.length - 1), tikuTypeLabel];
    }
    return categoryLabels;
  });

  // 判断分类是否被选中
  const isSelected = (category, level) => {
    return selection.value[level]?.id === category.id
  }
</script>

<style scoped>
  .category {
    background-color: #fff;
    border-bottom: 1px solid #e5e5e5;
    padding-bottom: 15px;
    margin-top: 20px;
    margin-bottom: 20px;
  }

  .category-level {
    display: flex;
    gap: 1rem;
  }

  .category-label {
    width: 60px;
    flex-shrink: 0;
    padding: 6px 10px;
    font-size: 16px;
    line-height: 20px;
  }

  .category-list {
    display: flex;
    flex-wrap: wrap;
  }

  .category-item {
    padding: 6px 10px;
    margin-bottom: 10px;
    margin-right: 10px;
    border-radius: 4px;
    cursor: pointer;
    line-height: 20px;
  }

  .category-item:hover {
    background-color: #f5f5f5;
  }

  .category-item.active {
    background-color: var(--ui-BG-Main);
    color: white;
  }
</style>
